package net.xuzhen97.distributed.transaction.course.common.validator;

import net.xuzhen97.distributed.transaction.course.common.exception.CheckException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * dto 接口，如果参数验证失败将抛出{@link ConstraintViolationException}异常
 *
 * @author xuzhen97
 */
public interface IValidate {

    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 验证DTO参数.
     *
     * @throws ConstraintViolationException 验证不通过抛出异常
     */
    default void validate() throws ConstraintViolationException {
        Set<ConstraintViolation<IValidate>> violations = validator.validate(this);
        if (violations != null && !violations.isEmpty()) {
            StringBuilder errorMsg = new StringBuilder();
            for (ConstraintViolation error : violations) {
                errorMsg.append(error.getPropertyPath() + ", " + error.getMessage() + ";");
            }
            throw new CheckException(errorMsg.toString());
        }
    }
}